package com.diors.commons.config.xmlbean;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import javax.xml.bind.annotation.XmlRootElement;

import com.diors.commons.log.DiorsLogger;
import com.diors.commons.utils.XmlObjectUtil;

/**
 * xml引擎
 * @author	darren.ouyang
 * @data	2013-9-16
 */
public class XmlEngine 
{
	
	static final DiorsLogger log = DiorsLogger.getLogger(XmlEngine.class);
	
	private static String data = "./data/";
	
	private final static String DefaultFolderRoot = "defult_folder";
	
	/**
	 * 加载所有xml数据到Obj对象当中
	 * @param obj
	 * @create	2013-9-16	darren.ouyang
	 */
	public static void load(Object obj)
	{
		Class<? extends Object> clz = obj.getClass();
		
		for (Field field : clz.getDeclaredFields())
		{
			/* 不是静态参数就过滤掉 */
			if (!Modifier.isStatic(field.getModifiers()))
			{
				log.warn(new StringBuilder("无法加载xml对应字段,Manager中存在非静态字段！！--参数名[").
						append(field.getName()).append("]").toString());
				continue;
			}
			
			/* 存在是final参数的字段 */
			if(Modifier.isFinal(field.getModifiers()))
			{
				log.warn(new StringBuilder("无法加载xml对应字段,Manager中存在修饰符有final字段！！--参数名[").
						append(field.getName()).append("]").toString());
				continue;
			}

			/* 根据注解类型做出相应处理 */
			if (field.isAnnotationPresent(XmlFileData.class))
				processField(field, obj);
			else if (field.isAnnotationPresent(XmlFolderData.class))
				processFolderField(field, obj);
			else
				log.warn(new StringBuilder("无法加载xml对应字段,Manager中存在字段没有xml相关注解！！--参数名[").
						append(field.getName()).append("]").toString());
			
		}
	}
	
	/**
	 * 加载xml文件
	 * @param field	字段
	 * @param obj	管理xml的对象
	 * @create	2013-9-16	darren.ouyang
	 */
	private static void processField (Field field, Object obj)
	{
		boolean oldAccessible = field.isAccessible();
		
		field.setAccessible(true);
		/**得到域的注解对象**/
		XmlFileData fileData = field.getAnnotation(XmlFileData.class);
		/**判断路径是否合法**/
		if(fileData.path().isEmpty())
		{
			log.warn("XmlFileData " + field.getName() + " class " + field.getDeclaringClass().getName() + " leng为0");
		}
		else
		{
			/**判断路径是否存在，并读取该文件**/
			File file = new File(fileData.path());
			/**如果路径存在，则读取对象**/
			if(file.exists())
			{
				try
				{
					//给域赋值
					field.set(obj, XmlObjectUtil.XmlToJavaBean(file, field.getType()));
				} 
				catch (Exception e) 
				{
					/**如果路径不存在**/
					StringBuilder builder = new StringBuilder("类[").append(field.getDeclaringClass().getName());
					builder.append("]属性[").append(field.getName()).append("]的注解指定的文件[").append(fileData.path());
					builder.append("]无法转换。");
					log.error(builder.toString(), e);
				}
			}
			else
			{
				/**如果路径不存在**/
				StringBuilder builder = new StringBuilder("类[").append(field.getDeclaringClass().getName());
				builder.append("]属性[").append(field.getName()).append("]的注解指定的文件[").append(fileData.path());
				builder.append("]不存在。");
				log.warn(builder.toString());
			}
		}
		field.setAccessible(oldAccessible);
	}
	
	/**
	 * 加载xml文件夹
	 * @param field	字段
	 * @param obj	管理xml的对象
	 * @create	2013-9-16	darren.ouyang
	 */
	private static void processFolderField(Field field, Object obj)
	{
		boolean oldAccessible = field.isAccessible();
		
		field.setAccessible(true);
		/**得到域的注解对象**/
		XmlFolderData dataholder = field.getAnnotation(XmlFolderData.class);
		String folderName = null;
		String fileName = null;
		/**判断路径是否合法**/
		if(dataholder.folderName().isEmpty())
			log.warn("DataHolderFolder " + field.getName() + " class " + field.getDeclaringClass().getName() + " leng为0");
		else
			folderName = dataholder.folderName();
		if(dataholder.fileName().isEmpty())
		{
			int index = folderName.lastIndexOf("/");
			if(index == folderName.length() - 1)
			{
				fileName = data + folderName.substring(folderName.lastIndexOf("/", index - 1) + 1, index) + ".xml";
			}
			else
			{
				fileName = data + folderName.substring(index + 1, folderName.length()) + ".xml";
			}
		}
		else
		{
			fileName = dataholder.fileName();
		}
		File file = new File(folderName);
		if(file.exists())
		{
			XMLDataLoader loader = new XMLDataLoader();
			
			String rootElementName = "";
			Class<?> dataType = field.getType(); 
			XmlRootElement annot = dataType.getAnnotation(XmlRootElement.class);
			if (annot != null)
				rootElementName = annot.name();
			
			if (rootElementName == null || rootElementName.equals(""))
				rootElementName = DefaultFolderRoot;
			
			loader.doupdate(folderName, fileName, rootElementName);
			try
			{
				field.set(obj, XmlObjectUtil.XmlToJavaBean(fileName, field.getType()));
			}
			catch (Exception e)
			{
				e.printStackTrace();
			} 
		}
		else
		{
			/**如果路径不存在**/
			StringBuilder builder = new StringBuilder("类[").append(field.getDeclaringClass().getName());
			builder.append("]属性[").append(field.getName()).append("]的注解指定的文件[").append(dataholder.folderName());
			builder.append("]不存在。");
			log.warn(builder.toString());
		}
		field.setAccessible(oldAccessible);
	}
}
